﻿/*
* 作 者: 槐尧
* 公 司: 墨宇天城
* 创建时间: 2016/3/4 9:49:16
* 说明:  
*/

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using System.Net;

public class GameWindow : MonoBehaviour
{
    private List<FruitBuyNum> m_lstFruitNum = new List<FruitBuyNum>();
    public List<ScoreNumText> lstNumText;
    public List<FruitButton> lstFruitButton;

    public BoxRunManager boxManager;
    private ShowWanning showWanning;

    /// <summary>
    /// 奖励金币
    /// </summary>
    private int WinNum = 0;

    /// <summary>
    /// 剩余金币数量
    /// </summary>
    private int CoinNum = 0;

    /// <summary>
    /// 已下注金币数量
    /// </summary>
    private int AlreadybetCoin = 0;

    public GameState gameState;

    private LabController labcontroller;
    private int pos;



    private bool isOneButton = false;
    //是否是清空下注后第一次点击开始按钮
    private bool isOneStartButton = true;

    private bool IsInitCoin = false;
    void Awake()
    {
        SetState(GameState.Init);
        labcontroller = this.transform.GetComponent<LabController>();
        showWanning = this.transform.Find("ShowWanning").GetComponent<ShowWanning>();
        NetHelper.RegisterEvent(MessageName.ServerCoin, OnServerCoin);
    }

    private void OnServerCoin(Dictionary<string, object> message)
    {
        int coin = DictionaryUnity.GetSafeIntValue(message, "coin");
        InitCoin(coin);
    }

    void Start()
    {
        InitCoin(0);
        foreach (FruitButton fb in lstFruitButton)
        {
            fb.OnAddFruit = OnAddFruitNum;
            FruitBuyNum num = new FruitBuyNum();
            num.id = fb.fruitId;
            num.num = 0;
            m_lstFruitNum.Add(num);
        }
        RefreshProbability();
    }
    /// <summary>
    /// 刷新概率
    /// </summary>
    public void RefreshProbability()
    {
        foreach (FruitButton fb in lstFruitButton)
        {
            fb.SetText();
        }
        List<FruitData> fruitdata = FruitDataManager.Intstance.GetFruitDatalist();
        for (int i = 0; i < fruitdata.Count; i++)
        {
            if (fruitdata[i].iNum != 0)
            {
                boxManager.lstPosition[i].transform.Find("Text").GetComponent<Text>().text = "X" + fruitdata[i].iNum;
            }
        }
    }
    /// <summary>
    /// 初始化金币
    /// </summary>
    /// <param name="num"></param>
    public void InitCoin(int num)
    {
        CoinNum = num;
        if (IsInitCoin)
        {
            CoinNum -= AlreadybetCoin;
        }
        labcontroller.CoinInit(CoinNum);
    }

    private void OnAddFruitNum(int index, int fruitId)
    {
        if (gameState == GameState.Init && CoinNum > 0)
        {
            if (isOneButton == false)
            {
                ClearAll();
            }
            isOneButton = true;
            FruitBuyNum num = GetFruitNumById(fruitId);
            num.AddNum(1);
            ScoreNumText numText = GetNumTxtByIndex(index);
            numText.SetTextValue(num.num);
            labcontroller.DelCoin(1);
            AlreadybetCoin++;
            IsInitCoin = true;
        }
    }

    ScoreNumText GetNumTxtByIndex(int index)
    {
        return lstNumText.Find(m => m.index == index);
    }

    FruitBuyNum GetFruitNumById(int id)
    {
        return m_lstFruitNum.Find(m => m.id == id);
    }

    /// <summary>
    /// 点击按钮，清除所有下注
    /// </summary>
    public void OnClearAll()
    {
        if (gameState == GameState.Init)
        {
            if (isOneButton)
            {
                labcontroller.AddCoin(AlreadybetCoin);
            }
            ClearAll();
            SoundController.Instance.PlaySoundFromResource("Sound/s1");
        }
    }
    /// <summary>
    /// 清除所有下注
    /// </summary>
    public void ClearAll()
    {
        foreach (ScoreNumText b in lstNumText)
        {
            b.SetTextValue(0);
        }

        foreach (FruitBuyNum num in m_lstFruitNum)
        {
            num.RestNum();
        }
        AlreadybetCoin = 0;
        isOneStartButton = true;
    }
    /// <summary>
    /// 所有种类下注一个
    /// </summary>
    public void OnAddAll()
    {
        if (gameState == GameState.Init)
        {
            foreach (FruitButton fb in lstFruitButton)
            {
                if (CoinNum > 0)
                {
                    OnAddFruitNum(fb.index, fb.fruitId);
                }
            }
        }
    }
    /// <summary>
    /// 获得奖励减半
    /// </summary>
    public void OnSethalve()
    {
        if(labcontroller.coinNum>0&&gameState != GameState.Bigorsmalling&&gameState != GameState.Turning)
        {
            int value = labcontroller.winNum / 2;
            labcontroller.DelWin(value);
            labcontroller.AddCoin(value);
            showWanning.StopCor();
        }
    }
    #region  比大小
    public void OnBuyBig()
    {
        if (gameState != GameState.Bigorsmalling && gameState != GameState.Turning)
        {
            StartCoroutine(BigOrSmall(true, gameState));
        }
    }

    public void OnBuySmall()
    {
        if (gameState != GameState.Bigorsmalling && gameState != GameState.Turning)
        {
            StartCoroutine(BigOrSmall(false, gameState));
        }
    }
    /// <summary>
    /// 比大小
    /// </summary>
    /// <param name="isBig"></param>
    /// <returns></returns>
    public IEnumerator BigOrSmall(bool isBig, GameState gs)
    {
        showWanning.StopCor();
        int randomNum = 0;
        SetState(GameState.Bigorsmalling);
        for (int i = 0; i < 10; i++)
        {
            randomNum = Random.Range(1, 15);
            labcontroller.SetBigOrSmall(randomNum);
            SoundController.Instance.PlaySoundFromResource("Sound/run");
            yield return new WaitForSeconds(0.2f);
        }
        for (int index = 0; index < 5; index++)
        {
            randomNum = Random.Range(1, 15);
            labcontroller.SetBigOrSmall(randomNum);
            SoundController.Instance.PlaySoundFromResource("Sound/run");
            yield return new WaitForSeconds(0.5f);
        }
        SetState(gs);
        if (gameState == GameState.TurnCom || gameState == GameState.BigorSmallCom)
        {
            if (isBig)
            {
                if (randomNum > 7)
                    labcontroller.AddWin(labcontroller.winNum);
                else
                    labcontroller.DelWin(labcontroller.winNum);
            }
            else
            {
                if (randomNum <= 7)
                    labcontroller.AddWin(labcontroller.winNum);
                else
                    labcontroller.DelWin(labcontroller.winNum);
            }
            SetState(GameState.BigorSmallCom);
            SoundController.Instance.PlaySoundFromResource("Sound/D_STAR");
        }
    }
    #endregion
    /// <summary>
    /// 点击开始
    /// </summary>
    public void OnStart()
    {
        if (gameState == GameState.Init)
        {
            if (!IsStartClick())
                return;
            if (!isOneStartButton)
            {
                if (AlreadybetCoin > labcontroller.coinNum)
                    return;
                labcontroller.DelCoin(AlreadybetCoin);
            }
            else
            {
                isOneStartButton = false;
            }
            pos = FruitLogic.GetTagPos();
            pos = 9;
            boxManager.OnAddFruit = OnStop;
            boxManager.Run(pos, FruitEnumType.Fruit);
            SetState(GameState.Turning);
        }
        else if (gameState == GameState.TurnCom || gameState == GameState.BigorSmallCom)
        {
            labcontroller.SetBigOrSmall(0);
            labcontroller.AddCoin(labcontroller.winNum);
            labcontroller.DelWin(labcontroller.winNum);
            SetState(GameState.Init);
            showWanning.StopCor();

            SetServerCoin(labcontroller.coinNum);
            IsInitCoin = false;
        }


        SoundController.Instance.StopLoopSound();
    }

    void SetServerCoin(int num)
    {
        Dictionary<string, object> dic = new Dictionary<string, object>();
        dic["route"] = MessageName.ClientCoin;
        dic["coin"] = num;

        NetHelper.Send(MessageName.ClientCoin, dic);
    }
    /// <summary>
    /// 结束调用
    /// </summary>
    /// <param name="fruitEnumType"></param>
    public void OnStop(FruitEnumType fruitEnumType)
    {
        Debug.LogError(fruitEnumType);
        FruitData fd = FruitDataManager.Intstance.GetFruitData(pos);
        if (fd.iFruitId == FruitEnum.GoodLuck1)
        {
            StartCoroutine(Three());
        }
        else if (fd.iFruitId == FruitEnum.GoodLuck2)
        {
            StartCoroutine(Rerotation());
        }
        else
        {
            FruitBuyNum fruitBuyNum = GetFruitNumById((int)fd.iFruitId);
            int winnum;
            if (fd.iNum == 0)
            {
                winnum = fruitBuyNum.num * FruitDataManager.Intstance.GetdefaultPrice(pos);
            }
            else
            {
                winnum = fruitBuyNum.num * fd.iNum;
            }
            if (fruitEnumType == FruitEnumType.GoodLuck2)
            {
                winnum = winnum * 3;
            }
            labcontroller.AddWin(winnum);
            SetState(GameState.TurnCom);

        }
        if (labcontroller.winNum != 0)
        {
            showWanning.StartRandomImg();
            SoundController.Instance.PlaySoundFromResource("Sound/w" + RandomAudoBg());
        }
        isOneButton = false;

    }
    /// <summary>
    /// GoodLuck2
    /// </summary>
    /// <returns></returns>
    public IEnumerator Rerotation()
    {
        yield return new WaitForSeconds(0.5f);
        pos = FruitLogic.GetTagPos();
        boxManager.OnAddFruit = OnStop;
        boxManager.Run(pos, FruitEnumType.GoodLuck2);
    }
    #region   GoodLuck1
    int threeIndex = 0;
    public void Threetimes(FruitEnumType fruitEnumType)
    {
        int winnum = 0;
        FruitData fdthree = FruitDataManager.Intstance.GetFruitData(pos);
        FruitBuyNum fruitBuyNumthree = GetFruitNumById((int)fdthree.iFruitId);
        if (fdthree.iNum == 0)
        {
            winnum = fruitBuyNumthree.num * FruitDataManager.Intstance.GetdefaultPrice(pos);
        }
        else
        {
            winnum = fruitBuyNumthree.num * fdthree.iNum;
        }
        labcontroller.AddWin(winnum);
        threeIndex++;
        if (threeIndex > 2)
        {
            threeIndex = 0;
            StopCoroutine(Three());
            SetState(GameState.TurnCom);
            showWanning.StartRandomImg();
        }
        else
        {
            StartCoroutine(Three());
        }
    }
    public IEnumerator Three()
    {
        yield return new WaitForSeconds(0.5f);
        pos = FruitLogic.GetTagPos();
        while (pos == 9 || pos == 21)
        {
            pos = FruitLogic.GetTagPos();
            if (pos != 9 && pos != 21)
                break;
        }
        boxManager.OnAddFruit = Threetimes;
        boxManager.Run(pos, FruitEnumType.GoodLuck1);
    }
    #endregion

    /// <summary>
    /// 是否下注
    /// </summary>
    /// <returns></returns>
    public bool IsStartClick()
    {
        if (AlreadybetCoin == 0)
            return false;
        else
            return true;
    }
    public int RandomAudoBg()
    {
        return Random.Range(1, 10);
    }
    public void SetState(GameState state)
    {
        Debug.LogError("state:" + state);
        gameState = state;
    }
}